#!/bin/bash

# DataPlexus Simple Startup Script (Linux/Mac)
echo "================================================================"
echo "                    DataPlexus Startup Script"
echo "                  Data Lineage Analysis System"
echo "================================================================"
echo

# Check Python
echo "[1/4] Checking Python..."
if ! command -v python3 &> /dev/null; then
    echo "ERROR: Python3 not found. Please install Python 3.8+"
    exit 1
fi
echo "OK: Python3 is installed"

# Check Node.js
echo "[2/4] Checking Node.js..."
if ! command -v node &> /dev/null; then
    echo "ERROR: Node.js not found. Please install Node.js 16+"
    exit 1
fi
echo "OK: Node.js is installed"

# Start Backend
echo "[3/4] Starting backend service..."
cd backend
if command -v gnome-terminal &> /dev/null; then
    gnome-terminal --title="DataPlexus Backend" -- bash -c "echo 'DataPlexus Backend API'; echo 'Port: 8000'; echo 'API Docs: http://localhost:8000/docs'; echo; python3 main.py; exec bash" &
elif command -v osascript &> /dev/null; then
    osascript -e 'tell app "Terminal" to do script "cd \"'$(pwd)'\"; echo \"DataPlexus Backend API\"; echo \"Port: 8000\"; echo \"API Docs: http://localhost:8000/docs\"; echo; python3 main.py"' &
else
    echo "Starting backend in background..."
    python3 main.py &
fi
cd ..

# Wait for backend
echo "Waiting for backend to start..."
sleep 3

# Start Frontend
echo "[4/4] Starting frontend service..."
cd frontend
if command -v gnome-terminal &> /dev/null; then
    gnome-terminal --title="DataPlexus Frontend" -- bash -c "echo 'DataPlexus Frontend'; echo 'Port: 3000'; echo 'URL: http://localhost:3000'; echo; npm run dev; exec bash" &
elif command -v osascript &> /dev/null; then
    osascript -e 'tell app "Terminal" to do script "cd \"'$(pwd)'\"; echo \"DataPlexus Frontend\"; echo \"Port: 3000\"; echo \"URL: http://localhost:3000\"; echo; npm run dev"' &
else
    echo "Starting frontend in background..."
    npm run dev &
fi
cd ..

# Show completion message
echo
echo "================================================================"
echo "                    System Started Successfully!"
echo "================================================================"
echo
echo "Frontend:     http://localhost:3000"
echo "Backend API:  http://localhost:8000"
echo "API Docs:     http://localhost:8000/docs"
echo "Health Check: http://localhost:8000/health"
echo
echo "Note: Services are running in background/separate terminals."
echo "       Use 'pkill -f main.py' and 'pkill -f \"npm run dev\"' to stop."
echo

# Try to open browser
if command -v xdg-open &> /dev/null; then
    echo "Opening browser..."
    xdg-open http://localhost:3000 &
    sleep 1
    xdg-open http://localhost:8000/docs &
elif command -v open &> /dev/null; then
    echo "Opening browser..."
    open http://localhost:3000 &
    sleep 1
    open http://localhost:8000/docs &
fi

echo "Press any key to exit this launcher..."
read -n 1
